local dkjson = require"library.dkjson"

local tileset = class("TIleset"){
    name = "";
    texture = nil;
    quads = {};
    size_width = 16;
    size_height = 16;
    tile_width = 16;
    tile_height = 16;
}

function tileset:__init__(tileset_path)
    local config_file = love.filesystem.newFile(tileset_path.."/tile.json")
    if config_file then
        local texture = love.graphics.newImage(tileset_path.."/tile.png")
        local config = dkjson.decode(config_file:read(),1,nil)
        self.texture = texture;
        self.name = config.name
        self.size_width = config.size_width or 16
        self.size_height = config.size_height or 16
        self.tile_width = config.tile_width or 16
        self.tile_height = config.tile_height or 16

        local width = self.size_width * self.tile_width
        local height = self.size_height * self.tile_height
        local twidth = self.tile_width
        local wheight = self.tile_height
        for x = 0,self.size_width - 1 do
            for y = 0,self.size_height - 1 do
                local index = self:to_index(x,y)
                self.quads[index] = love.graphics.newQuad(
                    x * self.tile_width,y * self.tile_height,
                    twidth,wheight,
                    width,height
                )
            end
        end
    end
end

function tileset:to_index(x,y)
    return y * self.size_width + x
end

function tileset:draw(tile_index,...)
    local quad = self.quads[tile_index]
    if quad then
        love.graphics.draw(self.texture,quad,...)
    end
end

return tileset